﻿//通过不断刷新局部页面，向视图插入唯一id
setInterval(aa, 100);

function aa() {
    var x = 0;
    var index = $(".Index");
    for (x; x < index.length; x++) {
        index[x].innerText = x + 1;
        if ($('.one') == undefined) $('#add').show();
        else $('#add').hide();
    }
    var s = $("div[data-id='1']").length;
    var j = $("div[data-id='2']").length;
    var b = $("div[data-id='3']").length;
    $("#sum-questions").text(s + b + j);
    $("#sum-singleChoice").text(s);
    $("#sum-blank").text(b);
    $("#sum-judge").text(j);
};
 
//题目的边框，添加边框样式
$("div").on("mouseenter",
    ".light",
    function () {
        $(this).css("border-style", "outset");
    });
//移除边框样式
$("div").on("mouseleave",
    ".light",
    function () {
        $(this).css("border-style", "none");
    });

//选择题按钮样式
$("div").on("click",
    ".btn-single",
    function () {
        $(this).css("background-color", "rgb(2,230,230)").attr("data-value", "1");
        $(this).parent().parent().siblings().find("button").css("background-color", "rgb(255,255,255)").attr("data-value", 0);
    });

//选择题按钮
var arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N'];
$("div").on("click",
    ".choose-opacity",
    function () {
        $(this).removeClass("choose-opacity");
        $(this).find("button").addClass("btn-single");
        $(this).find("p").addClass("ChoiceValue");
        var txt = `<svg t="1637486080426" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2474" width="200" height="200">
                                <path d="M96 128h832v64H96zM128 256h768l-89.024 704H217.024z" p-id="2475"></path><path d="M384 64h256v96h-256z" p-id="2476"></path>
                            </svg>`;
        $(this).find(".close").html(txt);
        var num = $(this).parent().find("button").length;

        var tet1 = `<div class="div-single choose-opacity form-group">
                        <div class="div-float">
                            <button class="btn btn-single" type="button" data-value="0">`+ arr[num] + `</button>
                        </div>
                        <div class="div-float" style="width:85%;">
                            <p class="ChoiceValue p-text form-control" contenteditable="true"></p>
                        </div>
                        <a href="#" class="close close-single" data-dismiss="alert">
                            <svg t="1637486080426" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2474" width="200" height="200">
                                <path d="M96 128h832v64H96zM128 256h768l-89.024 704H217.024z" p-id="2475"></path><path d="M384 64h256v96h-256z" p-id="2476"></path>
                            </svg>
                        </a>
                    </div>`;
        $(this).after(tet1);
        return false;
    });

//选择题删除选项
$("div").on("click",
    ".close-single",
    function () {
        //先获取点击的父元素div
        var thisBtn = $(this).parent().parent();
        //再删除点击的元素
        $(this).parent().remove();
        //最后查询里面存在的元素
        var btn = thisBtn.find(".btn");

        for (var i = 0; i < btn.length; i++) {
            btn[i].innerText = arr[i];
        }
    });

    //填空题
    //$("div").on("change",
    //    ".CorrectValue",
    //    function () {
    //        var aaa = $(this);
    //        if (aaa.indexOf("\\n") >= 0) {
    //            alert(aaa + " 中有\n");
    //        }
    //    });

//双击恢复编辑
$(document).on("dblclick",
    ".one",
    function () {
        $(this).find(".QuestName").attr("contenteditable", "true").addClass("p-textarea");
        $(this).find(".ChoiceValue").attr("contenteditable", "true").addClass("p-text");
        $(this).find(".QuestAnalysis").attr("contenteditable", "true").addClass("p-textarea");
        $(this).find(".Contents").attr("contenteditable", "true").addClass("p-textarea");
        $(this).find(".Value").attr("contenteditable", "true").addClass("p-textarea");
        $(this).find(".CorrectValue").attr("contenteditable", "true").addClass("p-textarea");
        $(this).find(".tools").attr('data-hide','0').show();
    });

//批量给分
$("#setScore").click(function() {
    setScore();
});
function setScore() {
    layui.use('layer', function () {
        layer.open({
            type: 1
            , title: "批量给分"
            , closeBtn: false
            , area: ['40%', '60%']
            , shade: 0.6
            , id: 'LAY_score'
            , btn: ['确定','取消']
            , content: '<div class="row" style="width: 420px;padding: 20px;  line-height: 22px; margin-left:30px; margin-top:10px;font-weight: 300;">'
                + '<h3 style="text-align:center;margin:20px;">总分<b class="score-sum"></b>分</h3>'
                + '<div style="text-align:center;">'
                + '<div style="margin: 10px;">选择题：每题 <input type="text" class="score-singleChoice form-control" style="display:inline;height:30px;" value="0" /> 分，共 <b class="sum-singleChoice"></b> 题，共 <b class= "score-sum-singleChoice"></b> 分</div>'
                + '<div style="margin: 10px;">填空题：每题 <input type="text" class="score-judge form-control" style="display:inline;height:30px;" value="0" /> 分，共 <b class="sum-judge"></b> 题，共 <b class="score-sum-judge"></b> 分</div>'
                + '<div style="margin: 10px;">判断题：每题 <input type="text" class="score-blank form-control" style="display:inline;height:30px;" value="0" /> 分，共 <b class="sum-blank"></b> 题，共 <b class="score-sum-blank"></b> 分</div>'
                + '</div></div>'
            , btn1: function (index, layero) {
                $("div[data-id='1']").find(".score").val($(".score-singleChoice").val());
                $("div[data-id='2']").find(".score").val($(".score-blank").val());
                $("div[data-id='3']").find(".score").val($(".score-judge").val());
                clearInterval(timer);
                layer.close(index);
            }, btn2: function (index, layero) {
                clearInterval(timer);
                layer.close(index);
            }
        });
        $(".sum-singleChoice")[0].innerText = $("div[data-id='1']").length;
        $(".sum-blank")[0].innerText = $("div[data-id='2']").length;
        $(".sum-judge")[0].innerText = $("div[data-id='3']").length;
        var timer = setInterval(bb, 1000);
        function bb() {
            $(".score-sum-singleChoice")[0].innerText = Number($(".score-singleChoice").val()) * Number($(".sum-singleChoice").text());
            $(".score-sum-blank")[0].innerText = Number($(".score-blank").val()) * Number($(".sum-blank").text());
            $(".score-sum-judge")[0].innerText = Number($(".score-judge").val()) * Number($(".sum-judge").text());
            $(".score-sum")[0].innerText = Number($(".score-sum-singleChoice").text()) + Number($(".score-sum-blank").text()) + Number($(".score-sum-judge").text());
        }
    });
}

//设置难度
$("#setLevel").click(function() {
    setLevel();
});
function setLevel() {
    layui.use('layer', function () {
        layer.open({
            type: 1
            , title: "设置题目难度等级"
            , closeBtn: false
            , area: ['40%', '60%']
            , shade: 0.6
            , id: 'LAY_score'
            , btn: ['确定']
            , content: '<div class="row" style="width: 420px;padding: 20px;  line-height: 22px; margin-left:30px; margin-top:10px;font-weight: 300;">'
                +'</div>'
            , btn1: function (index, layero) {
                
                layer.close(index);
            }
        });
    });
}

//一键保存
$("#setSaveDB").click(function () {
    setSaveDB();
})
function setSaveDB() {
    var submitBtns = $(".submitForm");
    for (var i = 0; i < submitBtns.length;i++) {
        var dataTypeId = $("#data-Index-" + i).attr('data-id');
        questionData(i, dataTypeId);
        $('#data-Index-' + i).find('.tools').attr('data-hide','1').hide();
    }
}

//调整顺序
$("#setOrder").click(function() {
    setOrder();
});
function setOrder() {
    var oneQuestion = $('.one');
    var str = "";
    var oldOrder = [];
    var newOrder = [];
    for (var i = 0; i < oneQuestion.length; i++) {
        var questName = $(oneQuestion[i]).find('.QuestName').first().text().toString();
        var questId = $(oneQuestion[i]).find('.Index').first().attr('data-question-id');
        var questTypeId = $(oneQuestion[i]).attr('data-id');
        var questType = "";
        if (questTypeId == 1) questType = "选择题";
        else if (questTypeId == 2) questType = "判断题";
        else if (questTypeId == 3) questType = "填空题";
        var questStr = "";
        if (questName.length > 5) questStr = questName.substring(0, 19) + "...";
        else questStr = questName;
        if (i % 4 == 0) str += '<tr>';
        str += "<td><div class='div-order drag t1' data-Index='" + questId + "'> <h4 style='text-align:center;'> "+questType+"</h4 ><p>" + questStr + "</p></div></td>";
        if ((i+1) % 4 == 0) str += '</tr>';
        oldOrder.push(questId);
    }
    layui.use('layer', function () {
        layer.open({
            type: 1
            , title: "调整题目顺序"
            , closeBtn: false
            , area: ['60%', '60%']
            , shade: 0.6
            , id: 'LAY_score'
            , btn: ['确定','取消']
            , content: '<div class="row" id="drag" style="width: 100%;padding: 20px;  line-height: 22px; margin-left:30px; margin-top:10px;font-weight: 300;">'
                + '<table id="table1"> <colgroup><col width="160px;" /> <col width="160px;"/><col width="160px;" /> <col width="160px;" /></colgroup>'
                + str
                + '<tr></tr></table>'
                + '</div>'
            , btn1: function (index, layero) {
                var questOrder = $('.div-order');
                for (var i = 0; i < questOrder.length; i++) {
                    newOrder.push($(questOrder[i]).attr('data-Index'));
                }
                var allQuestion = [];
                var item = $('.one');
                for (var i = 0; i < newOrder.length; i++) {
                    for (var j = 0; j < item.length; j++) {
                        if ($(item[j]).find('.Index').attr('data-Question-Id') == newOrder[i]) {
                            var formData = $('#data-Index-' + j);
                            var choiceValue = "";
                            formData.find('.ChoiceValue').each(function () {
                                choiceValue += $(this).text() + "::";
                            });
                            var choiceChecked;
                            formData.find('.btn-single').each(function () {
                                if($(this).attr('data-value')=='1')
                                choiceChecked = $(this).text();
                            });
                            if (formData.attr('data-id') == 1) {
                                var quest = {
                                    QuestionId: newOrder[i],
                                    QuestionType: Number(formData.attr('data-id')),
                                    QuestionScore : formData.find('input[class="score"]').val(),
                                    QuestionLevel : formData.find('#level' + j).attr('level-data'),
                                    QuestionTitle : formData.find('.QuestName').text(),
                                    QuestionAnalysis : formData.find('.QuestAnalysis').text(),
                                    QuestionItems : choiceValue,
                                    QuestionAnswer : choiceChecked,
                                    QuestKeyWords : formData.parent().find('#keyWordsSG' + j).text()
                                }
                            } else if (formData.attr('data-id') == 2) {
                                var quest = {
                                    QuestionId : newOrder[i],
                                    QuestionType : Number(formData.attr('data-id')),
                                    QuestionScore : formData.find('input[class="score"]').val(),
                                    QuestionLevel : formData.find('#level' + j).attr('level-data'),
                                    QuestionTitle : formData.find('.QuestName').text(),
                                    QuestionAnalysis : formData.find('.QuestAnalysis').text(),
                                    QuestionItems : "",
                                    QuestionAnswer : formData.find(`input[name='CorrectValue${j}']:checked`),
                                    QuestKeyWords : formData.parent().find('#keyWordsTF' + j).text()
                                }
                            } else if (formData.attr('data-id') == 3) {
                                var quest = {
                                    QuestionId : newOrder[i],
                                    QuestionType : Number(formData.attr('data-id')),
                                    QuestionScore : formData.find('input[class="score"]').val(),
                                    QuestionLevel : formData.find('#level' + j).attr('level-data'),
                                    QuestionTitle : formData.find('.QuestName').text(),
                                    QuestionAnalysis : formData.find('.QuestAnalysis').text(),
                                    QuestionItems : "",
                                    QuestionAnswer : formData.find('.CorrectValue').text(),
                                    QuestKeyWords : formData.parent().find('#keyWordsBL' + j).text()
                                }
                            }
                            allQuestion.push(quest);
                        }
                    }
                    
                }
                $('.one').each(function () {
                    $(this).remove();
                });
                ShowQuestion(true,allQuestion);
                layer.close(index);
                layer.msg("调整顺序后，请确定后重新保存");
            },
            btn2: function (index, layero) {
                layer.close(index);
            }
        });
        REDIPS.drag.init();
        REDIPS.drag.hover_color = '#E7C7B2';
        REDIPS.drag.drop_option = 'switching';
    });
}

//表单提交
$("div").on("click",
    ".submitForm",
    function () {
        var e = Number($(this).attr("data-Index"));

        var dataTypeId = $(this).parent().parent().attr('data-id');
        if (dataTypeId == 1) {
            if (!scoreVerify(e) || !titleVerify(e) || !checkVerify(e)) {
                return false;
            }
        } else if (dataTypeId == 2) {
            if (!scoreVerify(e) || !titleVerify(e)) {
                return false;
            }
        } else if (dataTypeId == 3) {
            if (!scoreVerify(e) || !titleVerify(e)) {
                return false;
            }
        }
        questionData(e, dataTypeId);

        //隐藏取消按钮和提交按钮
        $(this).parent().attr('data-hide', '1').hide();
    }
);

function questionData(e,dataTypeId) {
    var formData = $("#data-Index-" + e);
    var questionsIndex = e;
    var dataQuestionId = formData.find(".Index").attr("data-Question-Id");
    var score = formData.parent().find("input[class='score']");
    var level = formData.parent().find("#level" + e).attr("level-data");
    
    //改变属性，移除样式
    formData.find(".ChoiceValue").attr("contenteditable", "false").removeClass("p-text");
    formData.find(".QuestName").attr("contenteditable", "false").removeClass("p-textarea");
    formData.find(".QuestAnalysis").attr("contenteditable", "false").removeClass("p-textarea");
    formData.find(".CorrectValue").attr("contenteditable", "false").removeClass("p-textarea");

    var questName = formData.find(".QuestName");
    var questAnalysis = formData.find(".QuestAnalysis");
    var correctValue = formData.find(`input[name='CorrectValue${e}']:checked`);
    var choiceValue = [];
    formData.find(".ChoiceValue").each(function () {
        choiceValue.push($(this).text());
    });
    var option = [];
    var choiceChecked = [];
    formData.find(".btn-single").each(function () {
        option.push($(this).text());
        choiceChecked.push($(this).attr("data-value"));
    });

    //提交表单
    var quest;
    var keys;
    if (dataTypeId == 1) {
        keys = formData.parent().find("#keyWordsSG"+e);
        quest = {
            QuestionIndex: Number(questionsIndex), //题目顺序ID，唯一
            DataId: Number(dataQuestionId), //题目id，不唯一
            QuestType: Number(dataTypeId), //题目类型
            Options: option, //题目选项
            QuestName: questName.text(), //题目
            ChoiceValue: choiceValue, //题目选项值
            ChoiceChecked: choiceChecked, //题目选项答案
            QuestAnalysis: questAnalysis.text(), //题目解析
            TestDetailsId: Number(testPaperId), //试卷id
            Score: Number(score.val()), //分数
            Level: level,
            KeyWords: keys.text()
        };
    } else if (dataTypeId == 2) {
        keys = formData.parent().find("#keyWordsTF" + e);
        quest = {
            QuestionIndex: Number(questionsIndex),
            DataId: Number(dataQuestionId),
            QuestType: Number(dataTypeId),
            QuestName: questName.text(),
            CorrectValue: correctValue.val(),
            QuestAnalysis: questAnalysis.text(),
            TestDetailsId: Number(testPaperId),
            Score: Number(score.val()),
            Level: level,
            KeyWords: keys.text()
        }
    } else if (dataTypeId == 3) {
        keys = formData.parent().find("#keyWordsBL" + e);
        quest = {
            QuestionIndex: Number(questionsIndex),
            DataId: Number(dataQuestionId),
            QuestType: Number(dataTypeId),
            QuestName: questName.text(),
            CorrectValue: formData.find(".CorrectValue").text(),
            QuestAnalysis: questAnalysis.text(),
            TestDetailsId: Number(testPaperId),
            Score: Number(score.val()),
            Level: level,
            KeyWords: keys.text()
        }
    }
    read(e,quest,'add');//查询操作，查询后根据结果，自动判断是添加数据，还是更新数据
    return false;
}

//分数非空验证
function scoreVerify(e) {
    var scoreIndex = document.getElementsByClassName('score')[e];
    if ($(scoreIndex).val() == "") {
        layer.msg("第" + (e + 1) + "题的题目分数不能为空");
        return false;
    }
    return true;
}

//题目非空验证
function titleVerify(e) {
    var title = document.getElementsByClassName('QuestName')[e];
    if ($(title).text() == "") {
        layer.msg("第" + (e + 1) + "题的题目不能为空");
        return false;
    }
    return true;
}

//题目选项非空验证
function checkVerify(e) {
    var one = $('.one');
    var check = $(one[e]).find('.div-single');
    for (let i = 0; i < check.length; i++) {
        var checkItem = $(check[i]).find('.btn-single');
        if ($(checkItem[0]).attr('data-value') == '1') {
            return true;
        }
    }
    layer.msg("第" + (e + 1) + "题的选项里面没有选择答案");
    return false;
}